import Axios from "axios";
import store from '../store/store.js'
import router from 'vue-router'
Axios.defaults.timeout = 5000;
Axios.defaults.withCredentials = true;
Axios.defaults.headers.common['Type'] = 3
Axios.defaults.headers.post['Content-Type'] = 'application/json'
Axios.defaults.headers.common['Authorization'] = store.state.Authorization
const httpServer = (opts, data) => {
    var httpDefaultOpts = ''
    if (opts.method === 'post' || opts.method === 'put' || opts.method === 'delete') {
        httpDefaultOpts = {
            method: opts.method,
            url: opts.url,
            data: data
        }
    } else if (opts.method === 'get') {
        httpDefaultOpts = {
            method: opts.method,
            url: opts.url,
            params: data
        }
    }
    return new Promise(function (resolve, reject) {
        Axios(httpDefaultOpts).then(
            (res) => {
                resolve(res)
            }
        ).catch(
            (err) => {
                reject(err)
            }
        )
    })
}
// 添加请求拦截器
//option预检查，直接通过请求

Axios.interceptors.request.use(config => {
    // 在发送请求之前做些什么
    // 判断是否存在token，如果存在将每个页面header都添加token
    if (localStorage.getItem('Authorization')) {
        config.headers.Authorization = localStorage.getItem('Authorization')
    }
    return config
}, error => {
    // 对请求错误做些什么
    return Promise.reject(error)
})
// http response 拦截器
Axios.interceptors.response.use(response => {
    return response
}, error => {
    if (error.response) {
        switch (error.response.status) {
            case 403:
                localStorage.removeItem('Authorization');
                router.replace({
                    path: '/login',
                    query: { redirect: router.currentRoute.fullPath }// 登录成功后跳入浏览的当前页面
                })
        }
    }
    return Promise.reject(error.response.data)
})
export default httpServer;
